package org.paybiz.core.payplatform.yeePay.service;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.paybiz.constant.PayConstant;
import org.paybiz.constant.ErrorConstant;
import org.paybiz.core.payplatform.yeePay.bean.YeeBackResultDO;
import org.paybiz.core.service.callback.AbstractPayCallback;
import org.paybiz.model.PayResultDO;
import org.springframework.stereotype.Service;

/**
 * 支付回调
 * @author nassir.wen
 * @date 2013-1-8上午9:48:58
 * @company: MSD. 
 * @copyright: Copyright (c) 2013
 */
@Service("yeePayCallbackService")
public class YeePayCallbackServiceImpl extends AbstractPayCallback {

    private static final Log logger = LogFactory.getLog(YeePayCallbackServiceImpl.class);

    /**
     * @author nassir.wen
     * @date 2013-1-10下午2:56:40
     * @see org.paybiz.core.service.callback.msd.payCenter.msdPay.service.AbstractPayCallback#verifyResult(javax.servlet.http.HttpServletRequest)
     * @param request
     * @return
     */
    @Override
    protected PayResultDO verifyResult(HttpServletRequest request,HttpServletResponse response) {
        YeeBackResultDO resultDO = requestParamsParse(request);
        Integer result = 1; //1为失败 0为成功
        String errMsg = ""; //错误信息
        Integer sign = 1; //0 为私账 1为公账

        double payMoney = Double.valueOf(resultDO.getR3_Amt()) * 100;
        Integer money = (int) payMoney;

        //获取公账与私账标识
        if (resultDO.getR8_MP().trim() != null || !"".equals(resultDO.getR8_MP().trim())) {
            sign = Integer.parseInt(resultDO.getR8_MP().substring(resultDO.getR8_MP().length() - 1));
        }

        // 校验返回数据包
        boolean isOK = false;
        isOK = YeePayServiceImpl.verifyCallback(resultDO, sign);
        try {
            String order_id = resultDO.getR6_Order();
            if (isOK) {
                //判断订单状态是否成功 1为成功
                if (resultDO.getR1_Code().equals("1")) {
                    //交易成功
                    logger.info("订单号为：" + order_id + "易宝支付成功!");
                    result = 0;
                } else {
                    logger.info("订单号:" + order_id + "易宝支付未成功！");
                }
            } else {
                errMsg = ErrorConstant.SIGN_FAIL_ID;
                logger.info("订单号:" + order_id + "易宝支付交易签名被篡改！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        PayResultDO payResultDO = new PayResultDO();
        payResultDO.setPayMoney(money);
        payResultDO.setOrderId(resultDO.getR6_Order());
        payResultDO.setPaySerialId(resultDO.getR2_TrxId());
        payResultDO.setProductName(resultDO.getR5_Pid());
        payResultDO.setResult(result);
        payResultDO.setResultUrl(resultDO.getR8_MP());
        payResultDO.setPayType(PayConstant.YEEPAY);
        payResultDO.setErrMsg(errMsg);
        return payResultDO;
    }
    
    private YeeBackResultDO requestParamsParse(HttpServletRequest request) {
       //获取数据
        YeeBackResultDO resultDO = new YeeBackResultDO();
        try {
            resultDO.setR0_Cmd(formatString(request.getParameter("r0_Cmd"))); // 业务类型
            resultDO.setR1_Code(formatString(request.getParameter("r1_Code"))); // 支付结果
            resultDO.setR2_TrxId(formatString(request.getParameter("r2_TrxId"))); // 易宝支付交易流水号
            resultDO.setR3_Amt(formatString(request.getParameter("r3_Amt"))); // 支付金额
            resultDO.setR4_Cur(formatString(request.getParameter("r4_Cur"))); // 交易币种
            resultDO.setR5_Pid(new String(formatString(request.getParameter("r5_Pid")).getBytes("iso-8859-1"), "gbk")); // 商品名称
            resultDO.setR6_Order(formatString(request.getParameter("r6_Order"))); // 商户订单号
            resultDO.setR7_Uid(formatString(request.getParameter("r7_Uid"))); // 易宝支付会员ID
            resultDO.setR8_MP(new String(formatString(request.getParameter("r8_MP")).getBytes("iso-8859-1"), "gbk"));// 商户扩展信息
            resultDO.setR9_BType(formatString(request.getParameter("r9_BType"))); // 交易结果返回类型
            resultDO.setHmac(formatString(request.getParameter("hmac"))); // 签名数据
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        return resultDO;
    }
    
    String formatString(String text) {
        if (text == null) {
            return "";
        }
        return text;
    }
    
    /**
     * @author nassir.wen
     * @date 2013-1-10下午2:56:40
     * @see org.paybiz.core.service.callback.msd.payCenter.msdPay.service.AbstractPayCallback#send(int)
     * @param result
     * @return
     */
    @Override
    protected String send(int result) {
        // TODO Auto-generated method stub
        return null;
    }

}
